package com.egg.common.core.model.response;

import com.egg.common.core.enums.ResponseCode;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.Objects;

/**
 * Http请求返回数据泛型包装类
 */
@Data
public class ResponseData<T> implements Serializable {


    @ApiModelProperty(value = "响应码", notes = "com.egg.common.core.enums.ResponseCode")
    private Integer code;

    @ApiModelProperty(value = "消息提示")
    private String msg;

    @ApiModelProperty(value = "数据体")
    private T data;

    @ApiModelProperty(value = "是否成功")
    public boolean isSuccess() {
        return Objects.equals(this.code, ResponseCode.SUCCESS.getCode());
    }

    @ApiModelProperty(value = "是否失败")
    public boolean isError() {
        return !isSuccess();
    }

    public ResponseData(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ResponseData() {
    }

    public static <T> ResponseData<T> success() {
        ResponseData<T> rd = new ResponseData<>();
        rd.setCode(ResponseCode.SUCCESS.getCode());
        rd.setMsg(ResponseCode.SUCCESS.getMessage());
        return rd;
    }

    public static <T> ResponseData<T> success(T data) {
        ResponseData<T> er = success();
        er.setData(data);
        return er;
    }

    public static <T> ResponseData<T> success(T data, String msg) {
        ResponseData<T> er = success(data);
        er.setMsg(msg);
        return er;
    }

    public static <T> ResponseData<T> error() {
        ResponseData<T> result = new ResponseData<>();
        result.setCode(ResponseCode.SYSTEM_ERROR.getCode());
        result.setMsg(ResponseCode.SYSTEM_ERROR.getMessage());
        return result;
    }

    public static <T> ResponseData<T> error(ResponseCode code) {
        ResponseData<T> result = error();
        result.setCode(code.getCode());
        result.setMsg(code.getMessage());
        return result;
    }

    public static <T> ResponseData<T> error(String msg) {
        ResponseData<T> result = error();
        result.setCode(ResponseCode.CUSTOM_ERROR.getCode());
        result.setMsg(msg);
        return result;
    }

    public static <T> ResponseData<T> error(Integer code, String msg) {
        ResponseData<T> result = error();
        result.setCode(code);
        result.setMsg(msg);
        return result;
    }

    public static <T> ResponseData<T> error(Integer code, String msg, T data) {
        ResponseData<T> result = error();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);
        return result;
    }
}
